/*******************************************************************************
 * The MOSES project, model based software engineering of networked embedded systems.
 * 
 * Copyright (C) 2010-2013, University of Applied Sciences Wildau,
 * Telematics Research Group, http://www.tm.th-wildau.de/research-group
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses>.
 * 
 * Contributors:
 *     University of Applied Sciences Wildau - initial API and implementation
 * 
 * If you are interested in a commercial license please contact us via 
 * e-mail: ralf.vandenhouten@th-wildau.de.
 ******************************************************************************/
package de.thwildau.tm.moses.avro.ui.builder;

import java.io.File;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.ui.statushandlers.StatusManager;
import org.eclipse.xtext.builder.BuilderParticipant;
import org.eclipse.xtext.generator.IFileSystemAccess;
import org.eclipse.xtext.generator.OutputConfiguration;

import de.thwildau.tm.moses.avro.ui.Activator;
import de.thwildau.tm.moses.common.builder.IBuildContextVisitor;

/**
 * A Builder Participant, that compiles the given avro-file with the Avro Compiler. The (possible) error
 * messages of the Avro Compilers are added as Markers to the given Avro-file.
 * 
 * @author Thomas Kistel
 * @version $Revision: 766 $
 */
public class AvroBuildParticipant extends BuilderParticipant {
    
    private static final String AVPR_FILE = "avpr";
    private static final String AVDL_FILE = "avdl";

    @Inject
    private IBuildContextVisitor contextVisitor;
    
    @Inject
    private AvroSchemaCompilerTask schemaCompiler;
    
    @Inject
    private AvroIdlCompilerTask idlCompiler;


    public AvroBuildParticipant() {
    }

    /*
     * (non-Javadoc)
     * @see IXtextBuilderParticipant#build(IXtextBuilderParticipant.IBuildContext, IProgressMonitor)
     */
    @Override
    public void build(IBuildContext context, IProgressMonitor monitor) throws CoreException {
        super.build(context, monitor);
        Map<String, OutputConfiguration> outputConfigurations = getOutputConfigurations(context);
        OutputConfiguration outputConfig = outputConfigurations.get(IFileSystemAccess.DEFAULT_OUTPUT);
        if(outputConfig == null)
            return;
        
        IProject project = context.getBuiltProject();
        String targetDir = outputConfig.getOutputDirectory();
        IFolder targetFolder = project.getFolder(targetDir);
        List<IFile> avroFiles = contextVisitor.getAffectedFiles(context, AVPR_FILE, AVDL_FILE);
        for (IFile avroFile : avroFiles) {
            try {
                // if the affected avro file is already in the target folder (src-gen)
                // then it was compiled by another builder and we should skip it
                if(!targetFolder.getFullPath().isPrefixOf(avroFile.getFullPath())) {
                    compileAvroFile(targetFolder, avroFile, monitor);    
                }
                
            } catch(CoreException e) {
                Activator.logError("Could not compile " + avroFile.getName(), e);
                if(e.getStatus().getSeverity() == IStatus.ERROR)
                    throw e;
                else {
                    StatusManager.getManager().addLoggedStatus(e.getStatus());
                }
            }
            
        }
        project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
    }

    private void compileAvroFile(IFolder targetFolder, IFile sourceFile, IProgressMonitor monitor) throws CoreException {
        File src = toFile(sourceFile, "Source File");
        File destDir = toFile(targetFolder, "Output Directory");
        
        AvroCompilerTask task = getCompilerTask(sourceFile);
        task.doCompile(src, destDir);
    }
    
    private AvroCompilerTask getCompilerTask(IFile sourceFile) {
        String fileExtension = sourceFile.getFileExtension();
        if(fileExtension.endsWith(AVPR_FILE))
            return schemaCompiler;
        else if(fileExtension.endsWith(AVDL_FILE))
            return idlCompiler;
        throw new IllegalArgumentException("Unknown file extension " + fileExtension);
    }

    private File toFile(IResource resource, String label) throws CoreException {
        IPath location = resource.getLocation();
        if (location == null) {
            String msg = "The location of " + label + " (" + resource.getFullPath().toPortableString() + ") cannot  be determined.";
            throw new CoreException(new Status(IStatus.ERROR, Activator.getBundleId(), msg));
        }
        
        File file = location.toFile();
        if (!file.exists()) {
            String message = "Could not compile Avro file, because " + label + " (" + file.getAbsolutePath() + ") does not exist";
            throw new CoreException(new Status(IStatus.ERROR, Activator.getBundleId(), message));
        }
        return file;
    }
}
